﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
namespace DAO
{
    public class DataProvider
    {
        private static OleDbConnection _cnn;
        public DataProvider()
        {
            _cnn = new OleDbConnection();
            string cnnstring = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Database 3.2.accdb";
            _cnn.ConnectionString = cnnstring;
        }

        public DataTable ExecuteQuery(string query)
        {
            DataTable dt = new DataTable();
            try
            {
                _cnn.Open();
                OleDbDataAdapter adapter = new OleDbDataAdapter(query, _cnn);
                adapter.Fill(dt);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + "\n" + "Query bi sai " + "\n" + query);
            }
            finally
            {
                _cnn.Close();
            }
            return dt;
        }
        public bool ExecuteNonQuery(string query)
        {
            //string thongbao = "";
            try
            {
                _cnn.Open();
                OleDbCommand command = new OleDbCommand(query, _cnn);
                command.ExecuteNonQuery();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + "\n" + "Query bi sai " + "\n" + query);
                return false;
            }
            finally
            {
                _cnn.Close();
            }
            return true;
        }
        public object ExecuteScalar(string query)
        {
            object ketqua = null;
            try
            {
                _cnn.Open();
                DataTable dt = new DataTable();
                OleDbDataAdapter adapter = new OleDbDataAdapter(query, _cnn);
                adapter.Fill(dt);
                return dt.Rows[0][0];
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.Message);                
            }
            finally
            {
                _cnn.Close();
            }
            return ketqua;
        }

    }
}
